/*
 * @name: 管理后台登陆接口
 * @content: 
 * @Author: joyce
 * @Date: 2020-03-11 11:22:37
 */
const express = require(`express`)
const router = express.Router()
let jwt = require("jsonwebtoken");
let config = require("../libs/config");
const Manager = require('../model/Manager')
/* GET users listing. */
//管理后台登录
router.post('/api/v1/user/login', async (req, res, next) => {
  //
  try {
    console.log(req.body)
    
    var user = await Manager.findOne({
      username: req.body.username
    });
    console.log(user)
    //  何时返回token  要根据自己的业务逻辑
    if (user !== null) {
      console.log(user.password)
      console.log(req.body)
      // 获取到用户信息后进行密码校对
      if (user.password == req.body.password) {
        let token = jwt.sign(
          {
            _id: user._id
          },
          config.secretOrPrivateKey,
          {
            expiresIn: "1 days"
          }
        );
        console.log(token)
        res.json({
          code: 200,
          token: token,
          user: user.toJSON()
        })
      } else {
        res.json({
          code: 400,
          message: "账号或密码错误!"
        });
      }
    } else {
      res.json({
        code: 400,
        message: "用户不存在,请重新登陆!"
      });
    }

  } catch (e) {
    
    res.status(500).send(e.toString());

  }
  //
})

//管理后台获得登录信息
router.post('/api/v1/user/info', async (reqs, res, next) => {
  console.log(reqs.body)
  var user = await Manager.findOne({
    _id: reqs.body.id
  });
  console.log(user)
  if (user !== null) {
    res.json({
      code: 200,
      data: user
    })
}
 

//
})
//管理后台获得登录信息
router.post('/api/v1/user/logout', async (req, res, next) => {
      res.json({
        code: 20000,
        data: 'success'
      })
  
  //
})


module.exports = router;
